package com.softa.service.business.impl;

import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageInfo;
import com.softa.dao.dto.OrderDTO;
import com.softa.dao.dto.ProductDTO;
import com.softa.dao.dto.SysUserDTO;
import com.softa.dao.mapper.base.OrderMapper;
import com.softa.dao.mapper.base.SysFileMapper;
import com.softa.dao.mapper.base.UserTryMapper;
import com.softa.dao.mapper.relation.business.OrderRelationMapper;
import com.softa.dao.model.Order;
import com.softa.dao.model.Product;
import com.softa.dao.model.SysFile;
import com.softa.dao.model.UserTry;
import com.softa.enummodel.OrderEnum;
import com.softa.service.business.OrderService;
import com.softa.service.business.UserTryService;
import com.softa.service.system.SysFileService;
import com.softa.service.system.SysMessageService;
import com.softa.service.thread.UploadFtpThread;
import com.softa.utils.CommonUtil;
import com.softa.utils.DateUtils;
import com.softa.vo.DataGridRequest;
import com.softa.vo.QueryRequest;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRelationMapper orderRelationMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserTryService userTryService;

    @Autowired
    private UserTryMapper userTryMapper;

    @Autowired
    private SysFileMapper sysFileMapper;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public PageInfo<OrderDTO> queryProductTypeByParam(DataGridRequest request, final QueryRequest queryRequest) {
	  PageInfo<OrderDTO> page = request.startPagePlugin().doSelectPageInfo(new ISelect() {
		@Override
		public void doSelect() {
                orderRelationMapper.selectByCondition(queryRequest);
		}
	  });
	  return  page;
    }

    @Override
    public List<OrderDTO> queryOrdersByParam(QueryRequest queryRequest){
        List<OrderDTO> orderDTOS = orderRelationMapper.selectByCondition(queryRequest);
        for(OrderDTO orderDTO : orderDTOS){
            orderDTO.setPicFirstId(sysFileService.getFirstPicId(orderDTO.getId()));
        }
        return orderDTOS;
    }

    /**
     * 判断用户产品的试用次数
     */
    @Override
    public int getTryNumByUserAndProduct(OrderDTO orderDTO){
        //试用次数
        UserTry userTry = getUserTry(orderDTO);
        if(null != userTry){
            int trynum = getTryNum(userTry);
            if(trynum>2){
                return 2;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }

    /**
     *  创建订单
     *  用户曾经的试用次数，未满2次可直接试用
     */
    @Override
    public String createOrder(OrderDTO orderDTO) {
        //试用订单
        if(null != orderDTO.getType() && orderDTO.getType() == 1){
            //试用次数
            UserTry userTry = getUserTry(orderDTO);
            if(null != userTry){
                int trynum = getTryNum(userTry);
                if(trynum>2){
                    return "试用次数超限";
                }
                userTry.setNum(userTry.getNum() + 1);
                userTryMapper.updateByPrimaryKeySelective(userTry);
            }else{
                userTry = new UserTry();
                userTry.setNum(1);
                userTry.setProductId(orderDTO.getProductId());
                userTry.setUserId(orderDTO.getPurId());
                userTryMapper.insertSelective(userTry);
            }
        }

        //生成订单
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setNo(buildOrderNo(order.getType()));
        order.setDeleted(false);
        order.setVersion(1l);
        //插入的时候生成id
        orderRelationMapper.insertSelective(order);
        //生成附件
        buildFile(orderDTO.getPics(), order.getId());
        //上传文件到并保存消息记录
//        sysMessageService.saveMessage(orderDTO.getPurId(), getMessageContent());
        UploadFtpThread ftpThread = new UploadFtpThread(sysMessageService,orderDTO,redisTemplate,sysFileMapper);
        new Thread(ftpThread).start();
        return "提交成功";
    }

    /**
     * 获取消息模板内容
     * @return
     */
    public String getMessageContent(){
        StringBuilder sb = new StringBuilder();
        sb.append("您的产品【");
        sb.append("产品名称");
        sb.append("】");
        sb.append("【文件名称】");
        sb.append("已上传成功，提交时间：");
        sb.append(DateUtils.formatDate());
        return sb.toString();
    }

    /**
     * 获取试用次数
     */
    public int getTryNum(UserTry userTry){
        if(null == userTry){
           return 0;
        }else{
            if(userTry.getNum() == null || userTry.getNum() == 0){
               return 0;
            }else{
                return userTry.getNum();
            }
        }
    }

    public UserTry getUserTry(OrderDTO orderDTO){
       QueryRequest queryRequest = new QueryRequest();
       queryRequest.getParams().put("userId", orderDTO.getPurId());
       queryRequest.getParams().put("productId", orderDTO.getProductId());
       return userTryService.getUserTry(queryRequest);
    }

    /**
     * 保存附件
     */
    public void buildFile(List<Long> pics, Long id){
        if(CollectionUtils.isNotEmpty(pics)){
            for(Long picid : pics){
                saveSysFile(picid, id);
            }
        }
    }

    public void saveSysFile(Long fileId, Long orderId){
        SysFile sysFile = new SysFile();
        sysFile.setId(fileId);
        sysFile.setPkeyId(orderId.toString());
        sysFile.setTableName(Order.class.getSimpleName());
        sysFileMapper.updateByPrimaryKeySelective(sysFile);
    }

    /**
     *  订单编号
     * XX+20170617+12345（五位随机数）
     * @return
     */
    public String buildOrderNo(Integer type){
        StringBuilder sb = new StringBuilder();
        sb.append(OrderEnum.valueOf(type));
        sb.append(DateUtils.nowDateStryyyyMMdd(new Date()));
        sb.append(CommonUtil.getRandomNumber(5));
        return sb.toString();
    }
}
